package logic

import (
	"context"
	"gorm.io/gorm"
	"strconv"
	"three-sxp/models/mysql"

	"three-sxp/cartrpc/cartrpc"
	"three-sxp/cartrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCartLogic {
	return &CreateCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// CreateCart todo： 添加购物车
func (l *CreateCartLogic) CreateCart(in *cartrpc.CreateCartRequest) (*cartrpc.CreateCartResponse, error) {
	// todo: add your logic here and delete this line
	user, _ := mysql.GetUserInfo(mysql.User{
		Model: gorm.Model{ID: uint(in.UserId)},
	})
	if user.ID == 0 {
		return &cartrpc.CreateCartResponse{
			Code: 400,
			Msg:  "账号不存在",
		}, nil
	}
	goods, _ := mysql.GetGoodsInfo(mysql.Goods{
		Model: gorm.Model{ID: uint(in.GoodsId)},
	})
	if goods.ID == 0 {
		return &cartrpc.CreateCartResponse{
			Code: 400,
			Msg:  "商品不存在",
		}, nil
	}
	GoodsLen := mysql.Redis.LLen(context.Background(), "goods:"+strconv.Itoa(int(goods.ID))).Val()
	if GoodsLen < in.GoodsNum {
		return &cartrpc.CreateCartResponse{
			Code: 400,
			Msg:  "库存不足，无法添加到购物车",
		}, nil
	}
	cart, err := mysql.CreateCart(mysql.Cart{
		UserId: int(in.UserId),
	})
	if err != nil {
		return &cartrpc.CreateCartResponse{
			Code: 400,
			Msg:  "添加购物车失败",
		}, nil
	}
	_, err = mysql.CreateCartGoods(mysql.CartGoods{
		CartId:       int(cart.ID),
		GoodsName:    goods.GoodsName,
		GoodsPrice:   goods.GoodsPrice,
		GoodsStock:   goods.GoodsStock,
		GoodsDetails: goods.GoodsDetails,
	})
	if err != nil {
		return &cartrpc.CreateCartResponse{
			Code: 400,
			Msg:  "购物车商品添加失败",
		}, nil
	}
	//todo：扣除redis虚拟库存
	for i := 1; i <= int(in.GoodsNum); i++ {
		mysql.Redis.LPop(context.Background(), "goods:"+strconv.Itoa(int(goods.ID)))
	}
	return &cartrpc.CreateCartResponse{
		Code: 200,
		Msg:  "购物车添加成功",
	}, nil
}
